package com.group.controller;

import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import com.aliyuncs.afs.model.v20180112.AuthenticateSigRequest;
import com.aliyuncs.afs.model.v20180112.AuthenticateSigResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.exceptions.ServerException;
import com.base.view.BaseResult;
import com.base.view.GeneralResult;
import com.group.model.FriendShare;
import com.group.model.FriendShareLog;
import com.group.model.User;
import com.group.util.NoteException;

/**
 * 好友助力游戏
 * 
 * @author zhaolei
 *
 */
@Controller
public class FriendShareController extends BaseController {

	/**
	 * 创建分享助力游戏,如果当期用户的已经存在,则返回当前的
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping("/friendshare/add")
	@ResponseBody
	public GeneralResult<FriendShare> addFriendShare(HttpServletRequest request) {
		User user = getUser(request);

		FriendShare exist = beanDao.quickQueryOne(FriendShare.class, "userId", user.getId());
		if (exist != null) {
			// 添加助力日志
			FriendShareLog para = new FriendShareLog();
			para.setFriendShareId(exist.getId());
			para.setUserId(user.getId());
			exist.setLog(beanDao.queryOne(para));

			return new GeneralResult<FriendShare>().setValue(exist);
		}

		FriendShare fs = new FriendShare();
		fs.setUserId(user.getId());
		fs.setUserName(user.getName());
		fs.setNum(0d);
		beanDao.save(fs);

		// 添加助力日志
		FriendShareLog para = new FriendShareLog();
		para.setFriendShareId(fs.getId());
		para.setUserId(user.getId());
		fs.setLog(beanDao.queryOne(para));

		return new GeneralResult<FriendShare>().setValue(fs);
	}

	/**
	 * 获取分享助力游戏详情
	 * 
	 * @param friendShareId
	 * @return
	 */
	@GetMapping("/friendshare/id")
	@ResponseBody
	public GeneralResult<FriendShare> getFriendShare(Long friendShareId, HttpServletRequest request) {
		FriendShare exist = beanDao.quickQueryOne(FriendShare.class, "id", friendShareId);

		// 添加助力日志
		User user = getUser(request);
		FriendShareLog para = new FriendShareLog();
		para.setFriendShareId(friendShareId);
		para.setUserId(user.getId());
		exist.setLog(beanDao.queryOne(para));

		return new GeneralResult<FriendShare>().setValue(exist);
	}

	/**
	 * 点击领取或者好友助力
	 * 
	 * @param friendShareId
	 * @param request
	 * @return 币的个数
	 * @throws Exception
	 * @throws ServerException
	 */
	@GetMapping("/friendshare/num")
	@ResponseBody
	public GeneralResult<Double> getNum(Long friendShareId, String session, String sig, String token, String scene, HttpServletRequest request) throws ServerException, Exception {
		FriendShare fs = beanDao.quickQueryOne(FriendShare.class, "id", friendShareId);
		if (fs == null) {
			throw new NoteException("数据错误");
		}

		AuthenticateSigRequest srequest = new AuthenticateSigRequest();
		srequest.setSessionId(session);// 必填参数，从前端获取，不可更改，android和ios只变更这个参数即可，下面参数不变保留xxx
		srequest.setSig(sig);// 必填参数，从前端获取，不可更改
		srequest.setToken(token);// 必填参数，从前端获取，不可更改
		srequest.setScene(scene);// 必填参数，从前端获取，不可更改
		srequest.setAppKey("FFFF00000000017AE57E");// 必填参数，后端填写
		srequest.setRemoteIp("127.0.0.1");// 必填参数，后端填写

		AuthenticateSigResponse response = client.getAcsResponse(srequest);
		if (response.getCode() != 100) {
			throw new NoteException("滑动验证失败");

		}

		User user = getUser(request);

		FriendShareLog para = new FriendShareLog();
		para.setFriendShareId(friendShareId);
		para.setUserId(user.getId());
		FriendShareLog exist = beanDao.queryOne(para);

		if (exist != null) {
			return new GeneralResult<Double>().setValue(exist.getNum());
		}

		Random r = new Random();
		FriendShareLog log = new FriendShareLog();
		log.setFriendShareId(friendShareId);
		log.setUserId(user.getId());
		if (user.getId().longValue() == fs.getUserId().longValue()) {
			// 给自己助力
			Integer num = r.nextInt(61) + 180;
			log.setNum(num.doubleValue() / 10);
		} else {
			// 给好友助力

			// 上限180
			double amount = tickerDao.countShareAmount(friendShareId);
			if (amount > 180) {
				throw new NoteException("助力获得币的总数不能超过180");
			}

			Integer num = r.nextInt(11) + 20;

			// 计算助力次数
			int count = tickerDao.countShareTimes(friendShareId);
			if (count % 10 == 0)
				num = num * 2;

			// 计算用户助力次数
			int userHelps = tickerDao.countHelpTimes(user.getId());
			if (userHelps >= 3) {
				num = num / 2;
			}

			log.setNum(num.doubleValue() / 10);
		}
		beanDao.save(log);

		fs.setNum(fs.getNum() + log.getNum());
		beanDao.save(fs);

		return new GeneralResult<Double>().setValue(log.getNum());
	}

	/**
	 * 转出到钱包
	 * 
	 * @param friendShareId
	 * @return
	 */
	@GetMapping("/friendshare/ticker")
	@ResponseBody
	public synchronized BaseResult addTicker(Long friendShareId) {
		FriendShare fs = beanDao.quickQueryOne(FriendShare.class, "id", friendShareId);
		if (fs == null) {
			throw new NoteException("数据错误");
		}

		// if (fs.getNum().doubleValue() < 30) {
		// throw new NoteException("少于30个币不能转入到钱包");
		// }

		if (fs.getNum().doubleValue() < 0.01) {
			throw new NoteException("少于1个不能提现");
		}

		tickerService.addTicker(fs.getUserId(), "wecc", fs.getNum(), "好友助力转入", null);

		fs.setNum(0d);
		beanDao.save(fs);

		return new BaseResult();
	}

	/**
	 * 所有助力自动提现
	 * 
	 * @return
	 */
	@GetMapping("/friendshare/clean")
	@ResponseBody
	public BaseResult cleanFriendShare() {
		List<FriendShare> fslist = tickerDao.queryCleanFriendShareList();

		for (FriendShare fs : fslist) {
			tickerService.addTicker(fs.getUserId(), "czr", fs.getNum(), "好友助力转入", null);

			fs.setNum(0d);
			beanDao.save(fs);
		}

		return new BaseResult();
	}

}
